import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from '@/utils/request'
import { formatDate, formatDateTime } from '@/utils/format'

// 路由
const router = useRouter()
const route = useRoute()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 对话框可见性
const dialogVisible = ref(false)

// 对话框标题
const dialogTitle = ref('')

// 查询参数
const queryForm = reactive({
  page: 1,
  limit: 10,
})

// 跟进记录列表
const traces = ref<any[]>([])

// 总数
const total = ref(0)

// 跟进表单
const traceForm = reactive({
  id: '',
  title: '',
  content: '',
  next_time: '',
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入跟进主题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }],
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 新增跟进
const handleAdd = () => {
  dialogTitle.value = '新增跟进记录'
  // 重置表单
  Object.keys(traceForm).forEach(key => {
    ;(traceForm as any)[key] = ''
  })
  dialogVisible.value = true
}

// 编辑跟进
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑跟进记录'
  // 填充表单数据
  Object.keys(traceForm).forEach(key => {
    ;(traceForm as any)[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除跟进
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除跟进记录【${row.title}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // 调用新后端接口删除跟进记录
      const response = await axios.delete(`/customer/trace/delete/${row.id}`)

      if (response.data.code === 0) {
        ElMessage.success('删除成功')
        getTraces() // 重新加载数据
      } else {
        ElMessage.error(response.data.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  queryForm.limit = val
  getTraces()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  queryForm.page = val
  getTraces()
}

// 提交表单
const submitForm = () => {
  if (!formRef.value) return

  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        let response
        const customerId = route.params.id as string

        if (traceForm.id) {
          // 编辑跟进记录
          response = await axios.put(`/customer/trace/edit/${traceForm.id}`, traceForm)
        } else {
          // 新增跟进记录
          const params = { ...traceForm, customer_id: customerId }
          response = await axios.post('/customer/trace/add', params)
        }

        if (response.data.code === 0) {
          ElMessage.success(traceForm.id ? '编辑成功' : '新增成功')
          dialogVisible.value = false
          getTraces() // 重新加载数据
        } else {
          ElMessage.error(response.data.msg || (traceForm.id ? '编辑失败' : '新增失败'))
        }
      } catch (error) {
        ElMessage.error(traceForm.id ? '编辑失败' : '新增失败')
      }
    }
  })
}

// 获取跟进记录
const getTraces = async () => {
  try {
    loading.value = true

    const customerId = route.params.id as string

    // 调用新后端接口获取跟进记录
    const response = await axios.get(`/customer/trace/view`, {
      params: {
        customer_id: customerId,
        ...queryForm,
      },
    })

    if (response.data.code === 0) {
      traces.value = response.data.data
      total.value = response.data.count
    } else {
      ElMessage.error(response.data.msg || '获取跟进记录失败')
    }
  } catch (error) {
    ElMessage.error('获取跟进记录失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
const init = () => {
  getTraces()
}

// 组件挂载时初始化
onMounted(() => {
  init()
})

// 导出所有需要在模板中使用的变量和方法
export {
  // 响应式数据
  formRef,
  loading,
  dialogVisible,
  dialogTitle,
  queryForm,
  traces,
  total,
  traceForm,
  rules,

  // 方法
  goBack,
  handleAdd,
  handleEdit,
  handleDelete,
  handleSizeChange,
  handleCurrentChange,
  submitForm,
  formatDate,
  formatDateTime,
}
